# -*- coding: utf-8 -*-

# This code is part of qcloudlink.
#
# Copyright (c) 2017-2020 Origin Quantum Computing. All Right Reserved.
#

"""
__date:         2020/09/07
__author:       Miracle Shih
__corporation:  OriginQuantum
__usage:        qcloudlink log system
"""

import logging
import os
import sys
import time


class Singleton(type):
    def __init__(self, *args, **kwargs):
        self.__instance = None
        super().__init__(*args, **kwargs)

    def __call__(self, *args, **kwargs):
        if self.__instance is None:
            self.__instance = super().__call__(*args, **kwargs)
            return self.__instance
        else:
            return self.__instance


class LogSystem(metaclass=Singleton):
    def __init__(self, log_dispaly_level: int, log_file_level: int, log_path: str, log_time: str = '',
                 log_name: str = 'iqlog.txt', save_mode: str = 'a+'):
        if not os.path.exists(log_path):
            os.makedirs(log_path)

        self.log_display_level = log_dispaly_level
        self.log_file_level = log_file_level
        self.log_path = log_path
        self.log_name = log_name
        self.log_time = log_time
        self.save_mode = save_mode
        self.logger = logging.getLogger("logger")
        self.logger.setLevel(level=log_file_level)
        self.logformat = '%(asctime)s - %(levelname)s - %(message)s'
        self.logformat_d = '%(asctime)s - %(name)s - %(levelname)s ' \
                           '- ''%(lineno)d ''- ''%(module)s - ''%(funcName)s - %(message)s'
        # self.logformat = '%(message)s'
        self._file_handler()

    def __getattr__(self, item):
        # proxy of logging
        return getattr(self.logger, item)

    def check(self):
        current_time = time.strftime("%Y%m%d", time.localtime())
        if current_time != self.log_time:
            self.log_time = current_time
            self._file_handler()
            self._strem_handler()

    def _file_handler(self):
        file_handler = logging.FileHandler(self.log_path + self.log_time + self.log_name, mode='a+')
        file_handler.setLevel(level=self.log_file_level)
        formatter = logging.Formatter(self.logformat_d)
        file_handler.setFormatter(formatter)
        self.logger.addHandler(file_handler)


TODAY = time.strftime("%Y%m%d", time.localtime())

LOG_D = 20
LOG_F = 10
LOG_P = "D:/iq_aotucalibration/"

iqlog = LogSystem(LOG_D, LOG_F, LOG_P, log_time=TODAY)

iqlog.info(f'\n\nThe log storage path is "{LOG_P}"')
